package com.shinbada.modules.sys.web;

import com.shinbada.common.json.AjaxJson;
import com.shinbada.common.utils.MyBeanUtils;
import com.shinbada.core.security.shiro.annotation.OpenApi;
import com.shinbada.core.web.BaseController;
import com.shinbada.modules.sys.entity.SysConfig;
import com.shinbada.modules.sys.service.SysConfigService;
import com.shinbada.modules.sys.service.UserService;
import com.shinbada.modules.sys.utils.UserUtils;
import com.shinbada.modules.sys.vo.SysConfigVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 系统安全配置
 *
 * @author initcap
 * @date 2021/3/11 10:50
 */
@RestController
@RequestMapping("/sys/sysConfig")
@Api(tags = "系统安全配置")
public class SysConfigController extends BaseController {

    @Autowired
    private SysConfigService sysConfigService;

    @OpenApi
    @ApiOperation("【开放接口】系统安全配置列表")
    @GetMapping("queryById")
    public AjaxJson queryById() {
        return AjaxJson.success().put("config", SysConfigVo.of(UserUtils.getConfig()));
    }

    @RequiresPermissions("user")
    @PostMapping("save")
    @ApiOperation("保存系统安全配置")
    public AjaxJson save(SysConfig config) throws Exception {
        if (!UserUtils.getUser().isAdmin()) {
            return AjaxJson.error("系统安全配置只有超级管理员能修改");
        }
        if (config.getMultiAccountLogin() == null) {
            config.setMultiAccountLogin("0");
        }
        if (StringUtils.isNotBlank(config.getAdministratorPassword()) && !SysConfig.VIEW_PASSWORD.equals(config.getAdministratorPassword())) {
            config.setAdministratorPassword(UserService.entryptPassword(config.getAdministratorPassword()));
        } else {
            config.setAdministratorPassword(null);
        }
        SysConfig target = UserUtils.getConfig();
        MyBeanUtils.copyBeanNotNull2Bean(config, target);
        target.setIsNewRecord(false);
        sysConfigService.save(target);
        return AjaxJson.success("保存系统安全配置成功").put("config", target);
    }

    @RequiresPermissions("user")
    @GetMapping("getConfig")
    @ApiOperation("获取系统安全配置 当前访问地址已经废弃,请改用 /sys/sysSetting/pages 返回信息不变!")
    public AjaxJson getConfig() {
        return AjaxJson.error("当前访问地址已经废弃,请改用 /sys/sysSetting/pages 返回信息不变!");
    }

}
